﻿using Hetang.Areas.User.Models.Classes.Config;
using Hetang.Models.Authorize;
using Hetang.Models.Config;
using Hetang.Models.Interface;
using Hetang.Models.MailServer;
using Hetang.Models.Repository;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Hetang.Areas.User.Controllers
{
    [Authorize(Users = "person,company")]    
    public class AccountController : Controller
    {
        //
        // GET: /User/Account/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult ResetPwd(string status)
        {            
            return View();
        }

        [HttpPost]
        public ActionResult ResetPwd()
        {
            Email email = new Email();
            if (Request.Cookies["resetpwd"] == null)
            {
                IDatabaseRepository _dr = new DatabaseRepository();                
                if (_dr.GetLastHandleEmailCode(EmailType.ResetPassword) == null)
                {                    
                    if (email.SentEmail(EmailType.ResetPassword))
                    {
                        return RedirectToAction("resetpwd", new { status = "sent" });
                    }
                    else
                    {
                        return RedirectToAction("resetpwd", new { status = "unsent" });
                    }
                }
                else
                {
                    return RedirectToAction("resetpwd", new { exist = "true" });
                }
            }
            else
            {
                DateTime dt = new DateTime();
                if (DateTime.TryParse(Server.UrlDecode(Request.Cookies["resetpwd"].Value), out dt))
                {
                    MailServerConfig mailConfig = (MailServerConfig)ConfigurationManager.GetSection("mailServerGroup");

                    if ((DateTime.Now - dt).TotalMinutes <= mailConfig[0].ExpiresMinute)
                    {
                        return RedirectToAction("resetpwd", new { exist = "true" });
                    }
                    else
                    {
                        if (email.SentEmail(EmailType.ResetPassword))
                        {
                            return RedirectToAction("resetpwd", new { status = "sent" });
                        }
                        else
                        {
                            return RedirectToAction("resetpwd", new { status = "unsent" });
                        }
                    }
                }
                else
                {
                    return View("resetPwd");
                }
            }
        }
    }
}
